<template>
  <div class="stats-container">
    <!-- 数据卡片 -->
    <div class="data-cards">
      <el-card shadow="hover" class="card-online">
        <template #header>
          <div class="card-header">
            <el-icon>
              <User />
            </el-icon>
            <span>在线用户</span>
          </div>
        </template>
        <div class="card-content">
          <div class="main-value">{{ onlineCount }}</div>
          <div class="sub-text">当前活跃会话</div>
        </div>
      </el-card>

      <el-card shadow="hover" class="card-visits">
        <template #header>
          <div class="card-header">
            <el-icon>
              <DataLine />
            </el-icon>
            <span>总访问量</span>
          </div>
        </template>
        <div class="card-content">
          <div class="main-value">{{ totalVisits }}</div>
          <div class="sub-text">历史累计访问</div>
        </div>
      </el-card>
    </div>

    <!-- 登录记录表格 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="table-header">
          <span class="title">最近登录记录</span>
          <div class="controls">
            <el-button size="small" :icon="Refresh" @click="refreshData" :loading="loading">
              刷新
            </el-button>
            <el-switch v-model="autoRefresh" active-text="自动刷新" inactive-text="手动刷新">
            </el-switch>
          </div>
        </div>
      </template>

      <el-table :data="recentLogins" v-loading="loading" style="width: 100%" stripe>
        <el-table-column prop="time" label="登录时间" width="180">
          <template #default="{ row }">
            <div class="time-cell">
              <div>{{ formatTime(row.time) }}</div>
              <div class="time-ago">{{ timeAgo(row.time) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="用户">
          <template #default="{ row }">
            <div class="user-cell">
              <el-avatar :size="24" :src="row.avatar" />
              <span class="username">{{ row.account }}</span>
              <el-tag v-if="row.account === currentUser" size="mini" effect="dark">
                当前用户
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'warning'" size="small">
              {{ row.status === 1 ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { User, DataLine, Refresh } from '@element-plus/icons-vue'
import { getOnlineUserCount, getTotalVisits, getRecentLogins } from '@/apis/interview'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn' // 中文语言包
import relativeTime from 'dayjs/plugin/relativeTime' // 正确引入方式

dayjs.extend(relativeTime) // 扩展插件
dayjs.locale('zh-cn') // 设置语言

// 响应式数据
const onlineCount = ref(0)
const totalVisits = ref(0)
const recentLogins = ref([])
const loading = ref(false)
const autoRefresh = ref(true)
let refreshTimer = null

// 获取当前用户（模拟）
const currentUser = ref('admin')

// 方法
const fetchData = async () => {
  try {
    loading.value = true
    const [onlineRes, visitsRes, loginsRes] = await Promise.all([
      getOnlineUserCount(),
      getTotalVisits(),
      getRecentLogins()
    ])

    onlineCount.value = onlineRes.data
    totalVisits.value = visitsRes.data
    // 修改这里：直接使用 loginsRes.data 而不是 loginsRes.data.list
    recentLogins.value = processLoginData(loginsRes || [])
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}
const processLoginData = (data) => {
  return data.map(item => ({
    ...item,
    status: isActive(item.time) ? 1 : 0,
    avatar: generateAvatar(item.account)
  }))
}

const isActive = (time) => {
  return dayjs().diff(dayjs(time), 'hour') < 2
}

const generateAvatar = (username) => {
  // 模拟生成头像
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  const color = colors[username.length % colors.length]
  return `https://dummyimage.com/50x50/${color.slice(1)}/ffffff&text=${username.charAt(0).toUpperCase()}`
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const timeAgo = (time) => {
  return dayjs(time).fromNow()
}

const refreshData = () => {
  fetchData()
}

// 自动刷新控制
const startAutoRefresh = () => {
  refreshTimer = setInterval(fetchData, 30000)
}

const stopAutoRefresh = () => {
  clearInterval(refreshTimer)
}

// 生命周期
onMounted(() => {
  fetchData()
  startAutoRefresh()
})

onBeforeUnmount(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.stats-container {
  padding: 20px;
}

.data-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-content {
  padding: 10px 0;
}

.main-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.sub-text {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.time-cell {
  line-height: 1.4;
}

.time-ago {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  margin: 0 8px;
}
</style>